from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework import exceptions
import random
from . import constants
from meiduo_mall.utils.ytx_sdk.sendSMS import CCP
from celery_tasks.sms_code.tasks import send_sms_code


class SmsAPIView(APIView):
    """
    发送验证码
    """

    def get(self, request, mobile):
        # 1.判断60秒内是否发送过验证码
        # 链接redis数据库,保存数据有时间限制,链接的数据库sms是在dev中设置的
        redis_cli = get_redis_connection('sms')

        sms_flag = redis_cli.get('sms_flag_' + mobile)
        if sms_flag: raise exceptions.ValidationError('发送验证码过于频繁')

        # 2.生成随机６位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        # 2.1 存储验证码，和验证码标记,并且设置有效时间使用setex方法
        # redis_cli.setex('sms_'+mobile,constants.SMS_CODE_EXPRIES,sms_code)
        # 设置标记，存的值随便
        # redis_cli.setex('sms_flag_'+mobile,constants.SMS_FLAG_EXPRIES,1)

        # 使用管道方式和交互
        redis_pipeline = redis_cli.pipeline()
        redis_pipeline.setex('sms_' + mobile, constants.SMS_CODE_EXPRIES, sms_code)
        redis_pipeline.setex('sms_flag_' + mobile, constants.SMS_FLAG_EXPRIES, 1)

        # 执行
        redis_pipeline.execute()

        # 3.通过云通讯发送验证码
        # print(sms_code)
        # CCP.sendTemplateSMS(mobile,sms_code,constants.SMS_CODE_EXPRIES/60,1)
        send_sms_code.delay(mobile, sms_code, constants.SMS_CODE_EXPRIES / 60, 1)

        # 4. 返回响应
        return Response({'message': 'OK'})
